﻿/*******************************************************************************************
 * Copyright (c) 2006-2009 Alex Robson, Rob Simmons, Craig Israel, and Rachel Twyford
 *
 * Use of this software in any form requires that you have both 
 * read and agreed to the following terms:
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions: 
 *
 * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, 
 * this list of conditions and the following disclaimer in the 
 * documentation and/or other materials provided with the distribution.
 * Neither the name of Nvigorate nor the names of its contributors may 
 * be used to endorse or promote products derived from this software without 
 * specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ****************************************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Nvigorate.Relational.Provider
{
    public class StatefulList<T> : IList<T>, IStatefulList<T>, ICollection
    {
        #region Fields

        protected List<T> _deletedSet;

        protected List<T> _insertedSet;

        protected List<T> _internalList;

        #endregion

        #region Operators

        private object _syncRoot;

        private bool _isSynchronized;

        public static implicit operator List<T>(StatefulList<T> source)
        {
            return ((IList<T>) source) as List<T>;
        }

        #endregion

        #region Constructors

        public StatefulList()
        {
            _internalList = new List<T>();
        }

        public StatefulList(IEnumerable<T> source)
        {
            _internalList = new List<T>(source);
        }

        #endregion

        #region IStatefulList<T> Implementation

        public List<T> InsertedSet
        {
            get
            {
                if(_insertedSet == null)
                    _insertedSet = new List<T>();
                return _insertedSet;
            }
            set { _insertedSet = value; }
        }

        public List<T> DeletedSet
        {
            get
            {
                if (_deletedSet == null)
                    _deletedSet = new List<T>();
                return _deletedSet;
            }
            set { _deletedSet = value; }
        }

        #endregion

        #region IList<T> Implementation

        public T this[int index]
        {
            get { return _internalList[index]; }
            set { _internalList[index] = value; }
        }

        public void Add(T item)
        {
            if(!item.Equals(default(T)))
            {
                InsertedSet.Add(item);
                DeletedSet.Remove(item);
                _internalList.Add(item);
            }
        }

        public void Clear()
        {
            InsertedSet.Clear();
            DeletedSet.AddRange(this.Except(DeletedSet));
            _internalList.Clear();
        }

        public bool Contains(T item)
        {
            return _internalList.Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            _internalList.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return _internalList.Count; }
        }

        public int IndexOf(T item)
        {
            return _internalList.IndexOf(item);
        }

        public void Insert(int index, T item)
        {
            InsertedSet.Add(item);
            DeletedSet.Remove(item);
            _internalList.Insert(index, item);
        }

        public bool IsReadOnly
        {
            get { return (_internalList as ICollection<T>).IsReadOnly; }
        }

        public object[] GetAddedRelatives()
        {
            return _insertedSet == null ? new object[] {} : _insertedSet.Cast<object>().ToArray();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public IEnumerator<T> GetEnumerator()
        {
            return _internalList.GetEnumerator();
        }

        public object[] GetRemovedRelatives()
        {
            return _deletedSet == null ? new object[] { } : _deletedSet.Cast<object>().ToArray();
        }
        
        public bool Remove(T item)
        {
            var success = _internalList.Remove(item);
            if(success)
            {
                DeletedSet.Add(item);
                InsertedSet.Remove(item);
            }
            return success;
        }

        public void RemoveAt(int index)
        {
            var item = _internalList[index];
            _internalList.RemoveAt(index);
            InsertedSet.Remove(item);
            DeletedSet.Add(item);
        }

        #endregion

        #region Implementation of ICollection

        public void CopyTo(Array array, int index)
        {
            if (array == null)
            {
                throw new ArgumentNullException("array");
            }
            if (array.Rank != 1)
            {
                throw new ArgumentException("StatefulList.CopyTo does not support multi-dimensioned arrays.");
            }
            if (array.GetLowerBound(0) != 0)
            {
                throw new ArgumentException("StatefulList.CopyTo requires arrays which have a lower bound of 0.");
            }
            if (index < 0)
            {
                throw new ArgumentOutOfRangeException("index", index, "StatefulList.CopyTo requires an index of 0 or greater.");
            }
            T[] localArray = array as T[];
            if (localArray != null)
            {
                _internalList.CopyTo(localArray, index);
            }
            else
            {
                Type elementType = array.GetType().GetElementType();
                Type c = typeof(T);
                if (!elementType.IsAssignableFrom(c) && !c.IsAssignableFrom(elementType))
                {
                    throw new InvalidCastException(
                        string.Format("Array of {0} is not compatible with collection element type {1}",
                                      elementType.FullName, c.FullName));
                }
                object[] objArray = array as object[];
                if (objArray == null)
                {
                    throw new InvalidCastException(string.Format("Array of {0} could not be cast to an object[]",
                                                                 elementType.FullName));
                }
                int count = _internalList.Count;
                try
                {
                    for (int i = 0; i < count; i++)
                    {
                        objArray[index++] = _internalList[i];
                    }
                }
                catch (ArrayTypeMismatchException)
                {
                    throw new InvalidCastException(
                        string.Format("Array of {0} could not be populated from a collection of {1}",
                                      elementType.FullName, c.FullName));
                }
            }

        }

        public object SyncRoot
        {
            get
            {
                if (_syncRoot == null)
                {
                    ICollection items = _internalList;
                    if (items != null)
                    {
                        _syncRoot = items.SyncRoot;
                    }
                    else
                    {
                        Interlocked.CompareExchange(ref this._syncRoot, new object(), null);
                    }
                }
                return _syncRoot;
            }
        }

        public bool IsSynchronized
        {
            get { return _isSynchronized; }
        }

        #endregion

        public void ResetState()
        {
            InsertedSet.Clear();
            DeletedSet.Clear();
        }
    }
}
